<template>
  <Dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="团队成员导入"
    width="400"
  >
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      action="none"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'
import * as IctApi from '@/api/project/ict'
import { ElMessage, ElMessageBox } from 'element-plus'

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  fileList.value = []
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const props = defineProps({
  teamType: String
})

const emits = defineEmits(['getTeamData'])
/** 提交表单 */
const submitForm = async () => {
  if (fileList.value.length == 0) {
    ElMessage.error('请上传文件')
    return
  }
  // 提交请求
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
  formLoading.value = true
  const formData = new FormData()
  formData.append('type', props.teamType)
  formData.append('file', fileList.value[0].raw)
  const data = await IctApi.importTeamList(formData)
  ElMessage.success('导入成功！')
  emits('getTeamData', data)
  resetForm()
  dialogVisible.value = false
}

/** 上传错误提示 */
const submitFormError = (): void => {
  message.error('上传失败，请您重新上传！')
  formLoading.value = false
}

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false
  uploadRef.value?.clearFiles()
}

/** 文件数超出提示 */
const handleExceed = (): void => {
  message.error('最多只能上传一个文件！')
}

/** 下载模板操作 */
const importTemplate = () => {
  ElMessageBox.confirm('是否确认下载团队成员模版?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      ElMessage({
        type: 'info',
        message: '正在请求资源请稍后',
        duration: 500
      })
      const data = await IctApi.downloadTeam()
      download.excel(data, '团队成员模版.xls')
      setTimeout(() => {
        ElMessage.success('下载成功！')
        dialogVisible.value = false
      }, 1500)
      resetForm()
    })
    .catch(() => {
      ElMessage.info('已取消下载')
    })
}
</script>